<template>
  <view class="my-tabbar">
    <view class="tabbar-container">
      <view
        v-for="(item, index) in items"
        :key="index"
        class="tabbar-item"
        :class="{ active: index === activeIndex }"
        @click="onItemClick(item, index)"
      >
        <image class="tabbar-icon" :src="index === activeIndex ? item.selectedIconPath : item.iconPath" mode="aspectFit" />
        <text class="tabbar-text">{{ item.text }}</text>
      </view>
    </view>
  </view>
  
</template>

<script>
import tabbar from '@/util/tabbar.js'

export default {
  name: 'MyTabbar',
  data() {
    return {
      items: [],
      activeIndex: 0,
    };
  },
  methods: {
    // Refresh tabbar items and active index based on current route
    refresh() {
      this.items = tabbar.getCurrentTabbarItems();
      const pages = getCurrentPages();
      const currentPage = pages && pages.length > 0 ? pages[pages.length - 1] : null;
      const route = currentPage && currentPage.route ? currentPage.route : '';
      const idx = this.items.findIndex(i => i.pagePath === route);
      this.activeIndex = idx >= 0 ? idx : 0;
    },
    onItemClick(item, index) {
      if (index === this.activeIndex) return;
      tabbar.switchTab({
        url: '/' + item.pagePath,
      });
    },
  },
  created() {
    this.refresh();
    // Hide native tabbar if exists
    if (tabbar && typeof tabbar.hideNativeTabBar === 'function') {
      tabbar.hideNativeTabBar();
    }
    // Listen to global tabbar refresh events
    if (typeof uni !== 'undefined' && uni.$on) {
      uni.$on('tabbar:refresh', this.refresh);
    }
  },
  beforeDestroy() {
    if (typeof uni !== 'undefined' && uni.$off) {
      uni.$off('tabbar:refresh', this.refresh);
    }
  }
}
</script>

<style scoped lang="css">
.my-tabbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ffffff;
  border-top: 1rpx solid #eaeaea;
  z-index: 999;
}

.tabbar-container {
  display: flex;
  height: 120rpx;
}

.tabbar-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8f8f94;
}

.tabbar-item.active {
  color: #000000;
}

.tabbar-icon {
  width: 48rpx;
  height: 48rpx;
}

.tabbar-text {
  font-size: 22rpx;
  margin-top: 8rpx;
}
</style>


